package com.tiger.cloud.service.system;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tiger.cloud.common.mybatis.MybatisTigerAdminDao;
import com.tiger.cloud.common.mybatis.TigerAdminBaseService;
import com.tiger.cloud.common.token.PasswordHashUtil;
import com.tiger.cloud.dao.system.SysUserDao;
import com.tiger.cloud.model.system.SysUser;
import com.tiger.cloud.util.Exceptions;

@Service("sysUserService")
public class SysUserService extends TigerAdminBaseService<SysUser> implements ISysUserService{
    
    @Autowired
	private SysUserDao sysUserDao;

	@Override
	public MybatisTigerAdminDao<SysUser> getEntityDao() {
		return sysUserDao;
	}
	
	@Override
	public int update(SysUser entity) {
		super.update(entity);
		return 1;
	}
	
	@Override
	public int updatePassword(SysUser entity) {
		try {
			entity.setPassword(PasswordHashUtil.createHash(entity.getPassword()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw Exceptions.unchecked(e);
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
			throw Exceptions.unchecked(e);
		}
		return sysUserDao.update(entity);
	}
	
	/* 
	* <p>Title: insert</p>
	* <p>Description: </p>
	* @param entity
	* @return
	* @see com.tiger.cloud.service.ddd#insert(com.tiger.cloud.model.system.SysUser)
	*/ 
	@Override
	public int insert(SysUser entity){
		if(!StringUtils.isEmpty(entity.getPassword())){
			try {
				entity.setPassword(PasswordHashUtil.createHash(entity.getPassword()));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
				throw Exceptions.unchecked(e);
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
				throw Exceptions.unchecked(e);
			}
		}
		super.insert(entity);
		return 1;
	}
    
}